<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 消息发送
 * @author KevinBai
 */

class Emailsender extends MY_Luckydog {
	public function __construct() {
		parent::__construct();

		$this->check_login_status();
        $this->load->model('luckydog/Emailsender_model', 'emailsender');
	}

	public function index() {
        $_SESSION['v_menu'] = "email";
        $draft_byid = 0;
        $type = $this->input->get("type", TRUE) ? $this->input->get("type" ,TRUE) : 0;
        $draftid = $this->input->get("draftid", TRUE) ? $this->input->get("draftid" ,TRUE) : "";
        $id = $this->input->get("id", TRUE) ? $this->input->get("id" ,TRUE) : "";
         if(!empty($draftid))
        {
            $draft_byid = $this->emailsender->get_email_draft_byid($draftid);
        }
        $this->load->model('luckydog/User_model', 'user');
        $departmentList = $this->user->getDepartentList();
        $data = array(
            'type'=>$type,
            'id'=>$id,
            'draft_byid'=>$draft_byid,
            'draftid'=>$draftid,
            'departmentList'=>$departmentList
        );
		$this->load->view("luckydog/email/emailsender",$data);
	}
    /**
     * 执行群发
     * @author KevinBai
     * @param $type 0：发送  1：存草稿
     * @param $res 1：发送成功  2：存草稿成功
     */
     public function send_email()
     {
        $type = $this->input->post("type", TRUE) ? $this->input->post("type", TRUE) : "0";
        $to_userid = $this->input->post("toemail_userid", TRUE) ? $this->input->post("toemail_userid", TRUE) : "0";
        $draftid = $this->input->post("draftid", TRUE) ? $this->input->post("draftid", TRUE) : "0";
        $departmentid = $this->input->post("departmentid", TRUE) ? $this->input->post("departmentid", TRUE) : "0";
        $usernames = $this->input->post("usernames", TRUE) ? $this->input->post("usernames", TRUE) : "0";
        $tosendtype = $this->input->post("tosendtype", TRUE) ? $this->input->post("tosendtype", TRUE) : "0";

        $subject = $this->input->post("subject", TRUE) ? $this->input->post("subject", TRUE) : "";
        $content = $this->input->post("content") ? $this->input->post("content") : "";

        $data_fd['tosendtype'] = $tosendtype;
        $data_fd['from_userid'] = $_SESSION['adminUserInfo']['id'];    
        
        $data_fd['subject'] = $subject;
        $data_fd['content'] = $content;
        $data_fd['addtime'] = time();

        //针对来自草稿箱的数据处理
        if(!empty($draftid))
        {
            //存稿
            if(!empty($type) && !empty($draftid))
            {
                $data_fd['draft_status'] = 1;
                $res = $this->emailsender->update_data($draftid,$data_fd);
                $res = $this->pushMessage($draftid,$tosendtype,$departmentid,$usernames);
                if($res)
                {
                    $res = 2;
                }
            }
            //发送
            if(empty($type) && !empty($draftid))
            {
                $data_fd['draft_status'] = 0;
                $res = $this->emailsender->update_data($draftid,$data_fd);

                //执行消息推送
                $res = $this->pushMessage($draftid,$tosendtype,$departmentid,$usernames);
            }
        }
        else
        {
            //直接发送处理
            $data_fd['draft_status'] = $type;
            $draftid = $this->emailsender->insert_data($data_fd);

            //推送消息
            $res = $this->pushMessage($draftid,$tosendtype,$departmentid,$usernames);
        }
        echo $res;
     }

     public function pushMessage($draftid,$tosendtype = '',$departmentid = '',$usernames = ''){
        $data_push['type'] = 0;
        $data_push['typeid'] = $draftid;
        $data_push['from_userid'] = $_SESSION['adminUserInfo']['id'];
        $data_push['from_username'] = $_SESSION['adminUserInfo']['username'];
        $data_push['createtime'] = time();

        $userid_arr = [];
        $this->load->model('luckydog/User_model', 'user');
        $data['fields'] = 'AccountID';
        $data['tosendtype'] = $tosendtype;
        if($departmentid){
            $data['departmentid'] = $departmentid;
        }
        if($usernames){
            ;
            $data['usernames'] = "'".str_replace(",", "','", $usernames)."'";
        }
        $offset = 0;
        while($userList =$this->user->userList($data,$offset,20)){
            $insertData_arr = [];
            $offset += count($userList);
            foreach($userList as $user){
                $insertData_arr[] = "(".$data_push['type'].",".$data_push['typeid'].",".$user['AccountID'].",".$data_push['from_userid'].",".$data_push['createtime'].",'".$data_push['from_username']."')";
            }
            $insertData_str = !empty($insertData_arr)?implode(",", $insertData_arr):'';
            if($insertData_str){
                $res = $this->emailsender->do_push($insertData_str);    
            }
            if(!$userList || count($userList) <=20) break;
        }
        return $res?1:0;
     }


     /**
      * 历史记录表/草稿列表
      *@author KevinBai
      *@param $sortname 按照**排序
      *@param $order 排序类型
      *@param $type 0：发送  1：存草稿
      */
      public function emailsender_history() {
        $_SESSION['v_menu'] = 'email_history';
        $type = $this->input->get('type',TRUE) ? $this->input->get('type',TRUE) : "";
        
        $order = $this->input->get('order',TRUE) ? $this->input->get('order',TRUE) : "desc";
        $sortname = $this->input->get('sortname',TRUE) ? $this->input->get('sortname',TRUE): "";
        $per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 0;
        $limit = 20;
        $total_rows = $this->emailsender->get_history_cnt($type);
        $base_url = '/luckycat/emailsender/emailsender_history?type='.$type;
        $page_links = $this->create_page_links($base_url,$total_rows,$limit);
        $history_list = $this->emailsender->get_history_list($sortname,$order,"$per_page,$limit",$type);
        $data = array(
            'history_list'=>$history_list,
            'order'=>$order,
            'page_links'=>$page_links,
            'type'=>$type
            );
		$this->load->view("luckydog/email/emailsender_history",$data);
	}
    /**
     * 删除草稿记录
     */
    public function del_draft()
    {
        $id = $this->input->post("id", TRUE) ? $this->input->post("id" ,TRUE) : "";
        $res = $this->emailsender->del_draft($id);
        echo $res;
    }
    /**
      * 根据ID获取邮件内容信息
      *@author KevinBai
      *
      */
      public function emailsender_content() {
        $id = $this->input->post("id", TRUE) ? $this->input->post("id", TRUE) : "";
        $emailsender_info = $this->emailsender->get_emailsender_by($id);
        $res=json_encode(array('content'=>$emailsender_info['content']));
        echo $res;
	}


    	/**
	 * 将所有用户的email插入邮件列表
	 * @author Kevinbai
	 * @date 2014-4-28
    */
    public function data_handle(){
        $toemail_userid = $this->input->post("toemail_userid",TRUE);
        $min_step = $this->emailsender->get_min_step();
        $total_cnt = $this->emailsender->email_from_temp_cnt();
        $limit = 2500;

        if($toemail_userid == 1)
        {
            //简历
             //简历用户 邮件
            $this->mlDel(2);
            $this->mlDel(1);
            if(empty($total_cnt)){
                $sql = "SELECT email FROM qq_user WHERE email != '' AND email_status != 2 AND toemail_userid != 2 AND toemail_userid !=1";
                $query = $this->db->query($sql);
                $result = $query->result_array();
        
                $sql_r = "SELECT email FROM qq_resume_baseinfo WHERE email != ''";
                $query_r = $this->db->query($sql_r);
                $result_r = $query_r->result_array();
        		//数组合并
                $resume_list = array_merge_recursive($result,$result_r);
                $last_resume_list = array();
                //去除相同 并插入临时表        
                $step = 1;
                foreach ($resume_list  as $key=>$v){
        			if (!in_array($v['email'],$last_resume_list)){
        				$last_resume_list[] = $v['email'];
        			}
                }
                //数据插入优化处理    
                foreach($last_resume_list as $k=>$r)
                {
                    if(($k+1)%$limit == 0)
                        {
                            $step++;
                        }
                    $str_data .= "("."'".$r."'".",".$step.",".$toemail_userid."),";
                }
                $str_data = substr($str_data,0,-1);
                $sql_m = "insert into qq_email_temp (email,step,toemail_userid) values ".$str_data;  
                $this->db->query($sql_m);
          
            }
            $final_resume_list = $this->emailsender->get_email_from_temp($min_step,$limit); 
            foreach($final_resume_list as $rows)
            {
                $c_list[] = $rows['email'];
            }
            if ($c_list){
                $tmp_arr_b = array_chunk($c_list,80);
                foreach ($tmp_arr_b AS $kb=>$vb){
                    $email_str_b = "";
                    foreach($vb AS $value_b){
                        $email_str_b .= $value_b.";";
                    }
                    if ($email_str_b){
                        $this->mlAdd($email_str_b,1);
                    }
                }
            }
        
        }elseif($toemail_userid == 2){
            //企业
            //企业用户 邮件
             $this->mlDel(2);
             $this->mlDel(1);
             if(empty($total_cnt)){
               
                 $sql_b = "SELECT email FROM qq_user WHERE email != '' AND email_status != 2 AND toemail_userid = 1";
                $query_b = $this->db->query($sql_b);
                $result_b = $query_b->result_array();
        
                $sql_c = "SELECT email FROM qq_company_profile WHERE email != '' AND email_status != 2";
                $query_c = $this->db->query($sql_c);
                $result_c = $query_c->result_array();
        		//数组合并
                $company_list = array_merge_recursive($result_b,$result_c);
                
                $last_list = array();
                //去除相同
                $step = 1;
                foreach ($company_list  as $key=>$v){

        			if (!in_array($v['email'],$last_list)){
        				$last_list[] = $v['email'];
        			}
                }  
                
                //数据插入优化处理              
                foreach($last_list as $k=>$r)
                {
                    if(($k+1)%$limit == 0)
                        {
                            $step++;
                        }
                    $str_data .= "("."'".$r."'".",".$step.",".$toemail_userid."),";
                }
                $str_data = substr($str_data,0,-1);
                $sql_m = "insert into qq_email_temp (email,step,toemail_userid) values ".$str_data;  
                $this->db->query($sql_m);   
            }
            $final_company_list = $this->emailsender->get_email_from_temp($min_step,$limit); 
            foreach($final_company_list as $rows)
            {
                $c_list[] = $rows['email'];
            }
            if ($c_list){
                    $tmp_arr = array_chunk($c_list,80);
                    foreach ($tmp_arr AS $k=>$v){
                        $email_str = "";
                        foreach($v AS $value){
                            $email_str .= $value.";";
                        }
                        if ($email_str){
                            $this->mlAdd($email_str,2);
                        }
                    }
                }
        }
        echo "1";
    }
    
 
}


/* End of file emailsender.php */
/* Location : application/controllers/luckycat/emailsender.php */
